package org.neusoft.Interceptor;

import org.neusoft.entity.Users;
import org.neusoft.exception.AuthFailException;
import org.neusoft.mapper.UserMapper;
import org.neusoft.utils.JwtService;
import org.neusoft.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.neusoft.rsp.ResponseCode.NO_OPERATOR_AUTH;

/**
 * @AUTHOR 尹书岿
 * @DATE 2024/12/19 15:38
 * @DESCRIBE
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    JwtService jwtService;
    @Autowired
    UserMapper userMapper;

    private void throwAuthFailedException() throws AuthFailException {
        throw new AuthFailException(403,"token验证失败！");
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了preHandle方法");
        String token = request.getHeader("Authorization");
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        try {
            if (token != null){
                //验证token是否合法
                String userId = null;
                //验证token是否过期
                if (jwtService.validateToken(token)){
                    userId = jwtService.getSub(token);
                    Users users = userMapper.selectById(userId);
                    System.out.println("用户id为：" + users.getUsername());
                    //将用户信息存入线程变量中
                    UserUtils.setLoginUser(users);
                    return true;
                }else {
                    throwAuthFailedException();
                    return false;
                }
            }
            else {
                //对于GET请求的/api/articles接口，不需要登录即可访问
                if (requestURI.matches("/api/articles.*?")
                        && method.toLowerCase().equals("GET")){
                    return true;
                }else {
                    throwAuthFailedException();
                    return false;
                }
            }
        } catch (Exception e) {
            throwAuthFailedException();
            return false;
        } finally {

        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行了postHandle方法");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行了afterCompletion方法");
        //清除用户信息
        UserUtils.removeUser();
    }
}
